package com.sgb.kjwl.view.ui.activity.transport;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;

import androidx.lifecycle.ViewModelProvider;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.luck.picture.lib.tools.SdkVersionUtils;
import com.sgb.kjwl.R;
import com.sgb.kjwl.databinding.AppActAddSelfCarBinding;
import com.sgb.kjwl.model.entity.self.CarInfoEntity;
import com.sgb.kjwl.model.entity.transport.DrivingLicenseOCREntity;
import com.sgb.kjwl.utils.DefaultUtil;
import com.sgb.kjwl.utils.EntityConversion;
import com.sgb.kjwl.utils.GlideEngine;
import com.sgb.kjwl.utils.KeepLifecycle;
import com.sgb.kjwl.utils.MapUtils;
import com.sgb.kjwl.utils.NumberUtil;
import com.sgb.kjwl.utils.RangeFocusChangeListener;
import com.sgb.kjwl.view.constant.RequestCode;
import com.sgb.kjwl.view.constant.RouterKey;
import com.sgb.kjwl.view.ui.activity.self.CameraActivity;
import com.sgb.kjwl.view.ui.activity.self.logistics.AddCarActivity;
import com.sgb.kjwl.view.widget.ChoosePictureDialog;
import com.sgb.kjwl.view.widget.transport.AMapDialog;
import com.sgb.kjwl.viewmodel.transport.AddSelfCarViewModel;
import com.sgb.link.entity.AMapAddressEntity;
import com.swgk.core.common.base.BaseActivity;
import com.swgk.core.util.MLog;
import com.swgk.core.util.NullableUtil;
import com.swgk.core.util.UserOperating;

import java.io.File;
import java.util.List;

/**
 * @author: 杨畔
 * @date: 2021/10/9 09:59
 * @Description: 添加自营车辆
 */
public class AddSelfCarActivity extends BaseActivity<AddSelfCarViewModel, AppActAddSelfCarBinding> {
    //
    public static final int TYPE_MAIN = 1;//主页
    public static final int TYPE_SUB = 2;  //副页
    public static final int TYPE_ACTUAL = 3;//车辆45度图
    //选择图片类型 1:主页 2:副页 3:车辆45度图
    private int mType;
    private String address;

    public static void start(Context context) {
        start(context, 0);
    }

    public static void start(Context context, long no) {
        Intent intent = new Intent(context, AddSelfCarActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        if (no != 0) {
            intent.putExtra(RouterKey.NO, no);
        }
        context.startActivity(intent);
    }

    /**
     * 发布车辆跳转入口
     *
     * @param context
     * @param isPublish 是否是发布车辆
     */
    public static void start(Context context, boolean isPublish) {
        Intent intent = new Intent(context, AddSelfCarActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        intent.putExtra(RouterKey.BOOLEAN, isPublish);
        context.startActivity(intent);
    }


    @Override
    protected int layoutId() {
        return R.layout.app_act_add_self_car;
    }

    @Override
    protected void createViewModel() {
        mViewModel = new ViewModelProvider(this).get(AddSelfCarViewModel.class);
    }

    @Override
    protected void init() {
        //页面保活
        KeepLifecycle.attach(this, KeepLifecycle.CAMERA_KEEP_MODEL);
        initData();
        initEvent();
    }

    private void initEvent() {
        mBinding.actionBar.setOnBackClickListener(v -> finish());
        mBinding.setOnClick(this);
        //设置输入范围，失去焦点后自动补全
        mBinding.etAddCarWeight.setOnFocusChangeListener(new RangeFocusChangeListener(1, 999999999));
        mBinding.etAddCarLength.setOnFocusChangeListener(new RangeFocusChangeListener(1, 999999));
        mBinding.etCarPersonCharge.setText(UserOperating.getInstance().getUserRealName());
        mBinding.etPersonChargePhone.setText(UserOperating.getInstance().getPhone());

        //接口回调
        mViewModel.ldMain.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                mBinding.imgDel1.setVisibility(View.VISIBLE);
            } else {
                mBinding.imgDel1.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(mViewModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setVehicleLicense(url));
            showImage(mBinding.ivAddCarMain, url);
        });
        mViewModel.ldSub.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                mBinding.imgDel2.setVisibility(View.VISIBLE);
            } else {
                mBinding.imgDel2.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(mViewModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setDrivingLicensePage(url));
            showImage(mBinding.ivAddCarSub, url);
        });
        mViewModel.ldActual.observe(this, url -> {
            if (!TextUtils.isEmpty(url)) {
                mBinding.imgDel3.setVisibility(View.VISIBLE);
            } else {
                mBinding.imgDel3.setVisibility(View.GONE);
            }
            NullableUtil.ofNullable(mViewModel.ldCar.getValue()).ifPresent(carInfoEntity -> carInfoEntity.setCarImage(url));
            showImage(mBinding.ivAddCarActual, url);
        });
        //车辆详情信息
        mViewModel.ldCar.observe(this, carInfoEntity -> {
            if (carInfoEntity == null || carInfoEntity.getId() == 0) {
                return;
            }
            try {
                if (!TextUtils.isEmpty(carInfoEntity.getVehicleLicense())) {
                    mBinding.imgDel1.setVisibility(View.VISIBLE);
                } else {
                    mBinding.imgDel1.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(carInfoEntity.getDrivingLicensePage())) {
                    mBinding.imgDel2.setVisibility(View.VISIBLE);
                } else {
                    mBinding.imgDel2.setVisibility(View.GONE);
                }
                if (!TextUtils.isEmpty(carInfoEntity.getCarImage())) {
                    mBinding.imgDel3.setVisibility(View.VISIBLE);
                } else {
                    mBinding.imgDel3.setVisibility(View.GONE);
                }
                showImage(mBinding.ivAddCarMain, carInfoEntity.getVehicleLicense(), false);
                showImage(mBinding.ivAddCarSub, carInfoEntity.getDrivingLicensePage(), false);
                showImage(mBinding.ivAddCarActual, carInfoEntity.getCarImage(), false);
                //ocr车辆数据
                DrivingLicenseOCREntity ocrEntity = EntityConversion.modelA2B(carInfoEntity, DrivingLicenseOCREntity.class);
                if (ocrEntity == null) {
                    ocrEntity = new DrivingLicenseOCREntity();
                }
                mViewModel.ldOcr.postValue(ocrEntity);
            } catch (Exception e) {
                e.printStackTrace();
            }

        });
        //ocr识别结果
        mViewModel.ldOcr.observe(this, entity -> {
            if (entity == null) return;
            try {
                //ocr反显
                mBinding.llAddCarCheck.setVisibility(View.VISIBLE);
                mBinding.etAddCarNumber.setText(DefaultUtil.getString(entity.getImageCarNumber()));
                mBinding.etAddCarWeight.setText(TextUtils.isEmpty(entity.getImageApprovedLoadingQuality())
                        ? ""
                        : NumberUtil.trim0(entity.getImageApprovedLoadingQuality()));
                mBinding.etAddCarLength.setText(TextUtils.isEmpty(entity.getImageSizeL())
                        ? ""
                        : NumberUtil.trim0(entity.getImageSizeL()));
                mBinding.tvAddress.setText(TextUtils.isEmpty(entity.getImageVehicleAddress())
                        ? ""
                        : entity.getImageVehicleAddress());
                mBinding.archivesNumber.setText(entity.getImageNumber());
                MapUtils.searchByLocationName(this, mViewModel.ldOcr.getValue().getImageVehicleAddress(), new MapUtils.OnMapSearchListener() {
                    @Override
                    public void onGeocodeSearched(com.sgb.kjwl.model.entity.transport.AMapAddressEntity aMapAddressEntity) {
                        if (aMapAddressEntity != null) {
                            try {
                                mViewModel.ldCar.getValue().setImageVehicleLat(aMapAddressEntity.getLatitude());
                                mViewModel.ldCar.getValue().setImageVehicleLon(aMapAddressEntity.getLongitude());
                                mViewModel.ldCar.getValue().setProvinceName(aMapAddressEntity.getProvince());
                                mViewModel.ldCar.getValue().setProvinceNo(aMapAddressEntity.getProvinceNo());
                                mViewModel.ldCar.getValue().setCityName(aMapAddressEntity.getCity());
                                mViewModel.ldCar.getValue().setCityNo(aMapAddressEntity.getCityNo());
                                mViewModel.ldCar.getValue().setDistrictName(aMapAddressEntity.getDistrict());
                                mViewModel.ldCar.getValue().setDistrictNo(aMapAddressEntity.getDistrictNo());
                                mViewModel.ldCar.getValue().setDetailAddress(aMapAddressEntity.getSnippet());
                            } catch (Exception e) {

                            }

                        }
                    }

                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        });
    }

    private void initData() {
        //编辑车辆no
        long no = getIntent().getLongExtra(RouterKey.NO, 0);
        if (no != 0) {
            mViewModel.getCarDetail(this, no);
            mBinding.actionBar.setTitle("编辑车辆");
        } else {
            if (getIntent().getBooleanExtra(RouterKey.BOOLEAN, false)) {
                mBinding.actionBar.setTitle("发布车辆");
            }
            mViewModel.ldCar.postValue(new CarInfoEntity());
        }
    }

    @Override
    public void onMultiClick(View v) {
        if (v == mBinding.flAddCarMain) {
            showPictureDialog(R.drawable.img_xszy, TYPE_MAIN);
        } else if (v == mBinding.flAddCarSub) {
            showPictureDialog(R.drawable.img_xszfy, TYPE_SUB);
        } else if (v == mBinding.flAddCarActual) {
            showPictureDialog(R.drawable.img_sl_car, TYPE_ACTUAL);
        } else if (v == mBinding.tvAddCarSubmit) {
            clearAllFocus();
            //重新设置页面车辆信息
            NullableUtil.ofNullable(mViewModel.ldCar.getValue()).ifPresent(carInfoEntity -> {
                if (mBinding.etAddCarNumber.getText() != null) {
                    carInfoEntity.setCarNumber(mBinding.etAddCarNumber.getText().toString());
                } else {
                    carInfoEntity.setCarNumber(null);
                }
                if (mBinding.etAddCarWeight.getText() != null) {
                    carInfoEntity.setImageApprovedLoadingQuality(mBinding.etAddCarWeight.getText().toString());
                } else {
                    carInfoEntity.setImageApprovedLoadingQuality(null);
                }
                if (mBinding.etAddCarLength.getText() != null) {
                    carInfoEntity.setCarLen(NumberUtil.convertToDouble(mBinding.etAddCarLength.getText().toString()));
                } else {
                    carInfoEntity.setCarLen(0);
                }
            });

            mViewModel.ldCar.getValue().setLinkman(mBinding.etCarPersonCharge.getText().toString());
            mViewModel.ldCar.getValue().setLinkmanPhone(mBinding.etPersonChargePhone.getText().toString());

            if (!TextUtils.isEmpty(mBinding.archivesNumber.getText().toString())) {
                mViewModel.ldOcr.getValue().setImageNumber(mBinding.archivesNumber.getText().toString());
                mViewModel.ldCar.getValue().setImageNumber(mBinding.archivesNumber.getText().toString());
            } else {
                if (mViewModel.ldOcr.getValue() == null) {
                    mViewModel.ldOcr.setValue(new DrivingLicenseOCREntity());
                }
                mViewModel.ldOcr.getValue().setImageNumber("");
                mViewModel.ldCar.getValue().setImageNumber("");
            }
            if (mViewModel.ldCar != null && TextUtils.isEmpty(mViewModel.ldCar.getValue().getDetailAddress())) {
                if (TextUtils.isEmpty(mViewModel.ldOcr.getValue().getImageVehicleAddress())) {
                    mViewModel.authCar(AddSelfCarActivity.this);
                    return;
                }
                MapUtils.searchByLocationName(this, mViewModel.ldOcr.getValue().getImageVehicleAddress(), new MapUtils.OnMapSearchListener() {
                    @Override
                    public void onGeocodeSearched(com.sgb.kjwl.model.entity.transport.AMapAddressEntity aMapAddressEntity) {
                        if (aMapAddressEntity != null) {
                            try {
                                mViewModel.ldCar.getValue().setImageVehicleLat(aMapAddressEntity.getLatitude());
                                mViewModel.ldCar.getValue().setImageVehicleLon(aMapAddressEntity.getLongitude());
                                mViewModel.ldCar.getValue().setProvinceName(aMapAddressEntity.getProvince());
                                mViewModel.ldCar.getValue().setProvinceNo(aMapAddressEntity.getProvinceNo());
                                mViewModel.ldCar.getValue().setCityName(aMapAddressEntity.getCity());
                                mViewModel.ldCar.getValue().setCityNo(aMapAddressEntity.getCityNo());
                                mViewModel.ldCar.getValue().setDistrictName(aMapAddressEntity.getDistrict());
                                mViewModel.ldCar.getValue().setDistrictNo(aMapAddressEntity.getDistrictNo());
                                mViewModel.ldCar.getValue().setDetailAddress(aMapAddressEntity.getSnippet());
                                mViewModel.authCar(AddSelfCarActivity.this);
                            } catch (Exception e) {

                            }

                        }
                    }

                });
            } else {
                mViewModel.authCar(this);
            }
        } else if (v == mBinding.imgDel1) {
            mViewModel.ldMain.postValue("");
        } else if (v == mBinding.imgDel2) {
            mViewModel.ldSub.postValue("");
        } else if (v == mBinding.imgDel3) {
            mViewModel.ldActual.postValue("");
        } else if (v == mBinding.llAddress) {

            AMapDialog.launch(this, mViewModel.ldCar.getValue().getImageVehicleLat(), mViewModel.ldCar.getValue().getImageVehicleLon());

        }
    }

    /**
     * 图片选择
     */
    private void showPictureDialog(int pic, int type) {
        ChoosePictureDialog dialog = new ChoosePictureDialog(this, pic);
        dialog.setDialogClickCallBack(ids -> {
            if ("拍照".equals(ids)) {
                getTackPhoto(type);
            } else if ("从手机相册选择".equals(ids)) {
                getCerImage(type);
            }
        });
        dialog.show(getSupportFragmentManager(), "pic");
    }

    /**
     * 拍照
     */
    private void getTackPhoto(int type) {
        mType = type;
        if (mType == TYPE_MAIN) {
            CameraActivity.start(this, 1, "行驶证主页", PictureConfig.REQUEST_CAMERA);
        } else if (mType == TYPE_SUB) {
            CameraActivity.start(this, 1, "行驶证副页", PictureConfig.REQUEST_CAMERA);
        } else if (mType == TYPE_ACTUAL) {
            PictureSelector.create(this)
                    .openCamera(PictureMimeType.ofImage())
                    .loadImageEngine(GlideEngine.createGlideEngine())
                    .theme(R.style.picture_default_style)
                    .compress(true)//是否压缩
                    .minimumCompressSize(4 * 1024)//小于4M不压缩
                    .forResult(PictureConfig.CHOOSE_REQUEST);
        }
    }

    /**
     * 选择图片
     */
    private void getCerImage(int type) {
        mType = type;
        PictureSelector.create(this)
                .openGallery(PictureMimeType.ofImage())
                .loadImageEngine(GlideEngine.createGlideEngine())
                .theme(R.style.picture_default_style)
                .selectionMode(PictureConfig.SINGLE)
                .compress(true)//是否压缩
                .minimumCompressSize(4 * 1024)//小于4M不压缩
                .maxSelectNum(1)//判断还能选多少张图片
                .forResult(PictureConfig.CHOOSE_REQUEST);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode != RESULT_OK) return;
        String path = "";
        if (requestCode == PictureConfig.CHOOSE_REQUEST) {
            List<LocalMedia> imageList = PictureSelector.obtainMultipleResult(data);
            if (imageList == null || imageList.size() == 0) return;
            //获取压缩图片
            if (SdkVersionUtils.checkedAndroid_Q()) {
                path = imageList.get(0).getAndroidQToPath();
            } else {
                path = imageList.get(0).getCompressPath();
            }
        } else if (requestCode == PictureConfig.REQUEST_CAMERA) {
            path = data.getStringExtra("imagePath");
        } else if (requestCode == RequestCode.CODE_MAP) {
            AMapAddressEntity entity = AMapDialog.get(data);
            if ((entity.getSnippet().contains("省") || entity.getSnippet().contains("市"))) {
                address = entity.getSnippet();
            } else {
                address = entity.getAllProvince() + entity.getAllCity() + entity.getAllDistrict() + entity.getSnippet();
            }
            mBinding.tvAddress.setText(address);
            mViewModel.ldCar.getValue().setImageVehicleLat(entity.getLatitude());
            mViewModel.ldCar.getValue().setImageVehicleLon(entity.getLongitude());
            mViewModel.ldCar.getValue().setProvinceName(entity.getProvince());
            mViewModel.ldCar.getValue().setProvinceNo(entity.getProvinceNo());
            mViewModel.ldCar.getValue().setCityName(entity.getCity());
            mViewModel.ldCar.getValue().setCityNo(entity.getCityNo());
            mViewModel.ldCar.getValue().setDistrictName(entity.getDistrict());
            mViewModel.ldCar.getValue().setDistrictNo(entity.getDistrictNo());
            mViewModel.ldCar.getValue().setDetailAddress(address);
            mViewModel.ldOcr.getValue().setImageVehicleAddress(address);
        }
        if (TextUtils.isEmpty(path)) {
            return;
        }
        switch (mType) {
            case TYPE_MAIN:
                mViewModel.uploadFileWithOCR(this, new File(path));
                break;
            case TYPE_SUB:
            case TYPE_ACTUAL:
                mViewModel.uploadFile(this, new File(path), mType);
                break;
        }
    }

    /**
     * 展示图片
     */
    private void showImage(ImageView imageView, String path) {
        showImage(imageView, path, true);
    }

    private void showImage(ImageView imageView, String path, boolean checkOcr) {
        if (TextUtils.isEmpty(path)) {
            imageView.setImageResource(R.color.transparent);
            imageView.setBackgroundColor(Color.TRANSPARENT);
            return;
        }
        imageView.setBackgroundColor(Color.WHITE);
        Glide.with(this).load(path)
                .apply(new RequestOptions().centerCrop())
                .into(imageView);
        //车辆图片不触发ocr识别
        if (mType == TYPE_ACTUAL) return;
        //检查是否进行ocr
        if (checkOcr && mViewModel.ldCar.getValue() != null
                && !TextUtils.isEmpty(mViewModel.ldCar.getValue().getVehicleLicense())
                && !TextUtils.isEmpty(mViewModel.ldCar.getValue().getDrivingLicensePage())) {
            mViewModel.carOcr(this);
        }
    }
}
